package com.cwx.web;

import com.alibaba.fastjson.JSONObject;
import com.cwx.common.Json;
import com.cwx.dao.entity.Member;
import com.cwx.interfaces.Interface98;
import com.cwx.service.MemberService;
import com.cwx.utils.Tool;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created by code on 17-8-29.
 */
@Controller
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private CacheManager cacheManager;
    @Value("${toApplyUrl}")
    private String toApplyUrl;
    @RequestMapping("/verified")
    @ResponseBody
    public Json verified(String name, String idCard, HttpSession session ) {
        Member member = (Member) session.getAttribute("member");
        Json json = new Json();
        String resultStr = null;
        try {
            resultStr = Interface98.idCardSimple(name, idCard);
        } catch (IOException e) {
            e.printStackTrace();
            json.setCode("20000");
            json.setMessage("网站异常,请稍后重试!");
            return json;
        }
        System.out.println("----------------------");
        System.out.println(resultStr);
        System.out.println("----------------------");
        JSONObject result = JSONObject.parseObject(resultStr);
        if (result.getString("retCod").equals("1000")) {
            if (result.getJSONObject("data").getString("status").equals("1")) {
                member.setRealName(name);
                member.setIdCard(idCard);
                memberService.save(member);
                json.setCode("10008");
                json.setMessage("恭喜您实名认证成功!");
            } else {
                json.setCode("20010");
                json.setMessage("您的实名信息不一致,请检查您的姓名和身份证!");
            }
        } else {
            json.setCode("20000");
            json.setMessage("网站异常,请稍后重试!");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/bindBank")
    public Json bindBank(String bankCard, String codeParam, HttpSession session) {
        Member member = (Member) session.getAttribute("member");
        String code = session.getAttribute("code").toString();
        Json json = new Json();
        if (code != null && codeParam != null && code.toString().equals(codeParam)) {
            String resultStr = null;
            try {
                resultStr = Interface98.bankCardFourAPI(member.getRealName(), member.getIdCard(),member.getPhone(),bankCard);
            } catch (IOException e) {
                e.printStackTrace();
                json.setCode("20000");
                json.setMessage("网站异常,请稍后重试!");
                return json;
            }
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result.getString("retCod").equals("1000")) {
                if (result.getJSONObject("data").getString("status").equals("1")) {
                    member.setBankCard(bankCard);
                    memberService.save(member);
                    json.setCode("10009");
                    json.setMessage("恭喜您银行卡绑定成功!");
                } else {
                    json.setCode("20012");
                    json.setMessage("您的四要素不一致,请检查!");
                }
            } else if (result.getString("retCod").equals("1006")){
                json.setCode("20019");
                json.setMessage("请输入正确的银行卡号!");
            }else {
                json.setCode("20000");
                json.setMessage("网站异常,请稍后重试!");
            }
            cacheManager.getCache("phoneCache").evict(member.getPhone());
        } else {
            json.setCode("20006");//code erro
            json.setMessage("请输入正确的短信验证码!");
            return json;
        }

        return json;
    }

    @RequestMapping("/checkVerified")
    public Json checkVerified(HttpSession session){
        Member member = (Member) session.getAttribute("member");
        Json json = new Json();
        if (member.getRealName() == null || member.getIdCard() == null || member.getRealName().equals("") || member.getIdCard().equals("")){
            json.setCode("20011");
            json.setMessage("尚未实名认证");
        }else {
            json.setCode("10005");
            json.setMessage("已实名认证");
        }
        return json;
    }

    @RequestMapping("/refresh")
    @ResponseBody
    public Json refresh(HttpSession session){
        Json json = new Json();
        Member member = (Member) session.getAttribute("member");
        if (member == null){
            json.setCode("20013");
            json.setMessage("获取用户信息失败！");
        }else {
            long mid = member.getId();
            Member newMember = memberService.findById(mid);
//            JSONObject memberJson = (JSONObject)JSONObject.toJSON(newMember);
            JSONObject memberJson = new JSONObject();
            memberJson.put("phone",member.getPhone());
            memberJson.put("realName",member.getRealName());
            memberJson.put("bankCard",member.getBankCard());
            memberJson.put("idCard",member.getIdCard());
//            memberJson.remove("password");
//            memberJson.remove("salt");
//            memberJson.remove("id");
            json.setCode("10006");
            json.setMessage("获取用户信息成功！");
            json.setObj(newMember);
        }
        return json;
    }
    @RequestMapping("/qrcode")
    @ResponseBody
    public Json qrcode(HttpSession session){
        Json json = new Json();
        Member member = (Member) session.getAttribute("member");
        if (member.getRealName() == null || member.getIdCard() == null){
            json.setCode("20014");
            json.setMessage("请先完成实名认证！");
            return json;
        }
//        if (member.getBankCard() == null){
//            json.setCode("20015");
//            json.setMessage("请先绑定银行卡信息！");
//            return json;
//        }
        Cache cache = cacheManager.getCache("keyCache");
        String phone = member.getPhone();

        String key = Tool.Encrypt(phone + Tool.randomStrNum(10000000,99999999),"MD5","utf-8");
        cache.put(phone,key);
        String url = toApplyUrl + "/member/toApply/" + phone + "/" + key;
        try {
            BufferedImage bufferedImage = Tool.createZxing(800,800,url);
            json.setCode("10007");
            json.setMessage("生成二维码成功！");
            json.setObj(new String(org.apache.commons.codec.binary.Base64.encodeBase64(Tool.imageToBytes(bufferedImage,"png"))));
        } catch (WriterException | IOException e) {
            e.printStackTrace();
            json.setCode("20016");
            json.setMessage("生成二维码失败！");
        }
        return json;
    }
    @RequestMapping("/toApply/{phone}/{key}")
    public String apply(@PathVariable String phone,@PathVariable String key){
        Json json = new Json();
        Cache cache = cacheManager.getCache("keyCache");
        if (cache.get(phone) == null || cache.get(phone).get().toString() == null || !cache.get(phone).get().toString().equals(key)){
                return "/html/invalid";
        }else{
            return "/html/baseInfo";
        }
    }
    @RequestMapping("/next")
    public String next(){
        return "/html/workInfo";
    }

    @GetMapping("/invalid")
    public String invalid(){
        return "/html/invalid";
    }

    @GetMapping("/success")
    public String success(){
        return "/html/success";
    }
}
